package com.jzt.demo.config;

import com.jzt.gateway.utils.AuthUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * 作者：lizw <br/>
 * 创建时间：2020/06/30 16:03 <br/>
 */
@Slf4j
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("{} | body -> {}", request.getRequestURI(), IOUtils.toString(request.getReader()).length());
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                log.info("cookie -> {}={}", cookie.getName(), cookie.getValue());
            }
        }
        Enumeration<String> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String header = headers.nextElement();
            if ("one-id".equalsIgnoreCase(header) || "user-agent-id".equalsIgnoreCase(header) || "gw-token".equalsIgnoreCase(header)) {
                log.info("header -> {}={}", header, request.getHeader(header));
            }
        }
        log.info("当前登录用户: {}", AuthUtils.getCurrentAccount(request));
        return super.preHandle(request, response, handler);
    }
}
